package com.spring.cootask.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spring.cootask.web.model.CooTaskTable;
import com.spring.cootask.web.model.CooTaskUserTableWithBLOBs;
import com.spring.cootask.web.model.TaskTablebase;
import com.spring.cootask.web.model.TaskTablebaseDetail;
import com.spring.cootask.web.service.CooTaskTableService;
import com.spring.cootask.web.service.CooTaskUserTableService;
import com.spring.security.core.annotation.OaUserPermission;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.model.BaseResult;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WoJunyu on 2016/9/6.
 */
@Controller
@RequestMapping(value = "/cootasktable")
public class CooTaskTableController {

    @Resource
    private CooTaskTableService cooTaskTableService;

    @Resource
    private CooTaskUserTableService cooTaskUserTableService;

    /**
     * 录入信息主页
     *
     * @return
     */
    @OaUserPermission(value = "/cootasktable/userValue")
    @RequestMapping(value = "/userValue")
    public ModelAndView userValue(Model model, @RequestParam String fTaskHeadid, @RequestParam String fTaskUserid,
                                  @RequestParam String fromUserId, @RequestParam String fromUserName,
                                  @RequestParam String fromDeptId, @RequestParam String fromDeptName,
                                  @RequestParam String transferLevel, @RequestParam String transferMaxLevel,
                                  HttpServletRequest request) {
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        Map<String, Object> parm = Maps.newHashMap();
        parm.put("taskUserId", fTaskUserid);

        //获取自定义结构
        List<CooTaskTable> retL = cooTaskTableService.selectByParm(parm);
        //fTaskUserid = "21ee4fab-097c-4398-9899-bd66f6148fc1";
        //根据用户获取数据
        CooTaskUserTableWithBLOBs retV = cooTaskUserTableService.selectByPrimaryKey(fTaskUserid);
        if (retV != null && ApplicationUtils.isNotNull(retV)) {
            //json数据反序列化

            //JSON

            //JSONArray jlist=JSON.parseArray(retV.getJsonData());
            @SuppressWarnings("rawtypes")
            List<Map> list = JSONArray.parseArray(retV.getJsonData(), Map.class);

            // List<Map<String, Object>>  listretm = JSON.parseArray(retV.getJsonData(),Map<String, Object>.class);
            //JSON.parseObject(retV.getJsonData());
            //组合自定义字段和对应的值
            if (list.size() > 0) {
                // if(retm!=null){
                Map<String, Object> retm = list.get(0);
                for (CooTaskTable one : retL) {
                    for (Map.Entry<String, Object> entry : retm.entrySet()) {
                        //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                        if (entry.getKey().equals(one.getColumnCode())) {
                            one.setValue(ApplicationUtils.Object2String(entry.getValue()));
                        }
                    }
                }
            }
        }
        model.addAttribute("taskUserId", fTaskUserid);
        model.addAttribute("taskId", fTaskHeadid);
        model.addAttribute("deptId", oaUser.getUser_shopdept_id());
        model.addAttribute("fromUserId", fromUserId);
        model.addAttribute("fromUserName", fromUserName);
        model.addAttribute("fromDeptId", fromDeptId);
        model.addAttribute("fromDeptName", fromDeptName);
        model.addAttribute("transferLevel", transferLevel);
        model.addAttribute("transferMaxLevel", transferMaxLevel);
        model.addAttribute("dataList", retL);
        return new ModelAndView("main/cootask/table/uservalue");
    }

    /**
     * 展现页面（代码基本与主页一致）
     *
     * @param model
     * @param fTaskHeadid
     * @param fTaskUserid
     * @param request
     * @return
     */
    @OaUserPermission(value = "/cootasktable/show")
    @RequestMapping(value = "/show")
    public ModelAndView show(Model model, @RequestParam String fTaskHeadid, @RequestParam String fTaskUserid, HttpServletRequest request) {
        Map<String, Object> parm = Maps.newHashMap();
        parm.put("f_task_headID", fTaskHeadid);
        //获取自定义结构
        List<CooTaskTable> retL = cooTaskTableService.selectByParm(parm);
//        fTaskUserid = "21ee4fab-097c-4398-9899-bd66f6148fc1";
//        parm.put("f_task_userID", fTaskUserid);
        //根据用户获取数据
        CooTaskUserTableWithBLOBs retV = cooTaskUserTableService.selectByPrimaryKey(fTaskUserid);
        if (retV != null && ApplicationUtils.isNotNull(retV)) {
            //json数据反序列化
            Map<String, Object> retm = JSON.parseObject(retV.getJsonData());
            //组合自定义字段和对应的值
            if (retm != null) {
                for (CooTaskTable one : retL) {
                    for (Map.Entry<String, Object> entry : retm.entrySet()) {
                        if (entry.getKey().equals(one.getName())) {
                            one.setValue(ApplicationUtils.Object2String(entry.getValue()));
                        }
                    }
                }
            }
        }
        model.addAttribute("taskUserId", fTaskUserid);
        model.addAttribute("taskId", fTaskHeadid);
        model.addAttribute("dataList", retL);
        return new ModelAndView("main/cootask/table/show");
    }

    @RequestMapping(value = "/saveFormData")
    @ResponseBody
    public Object saveFormData(@RequestBody List<Map<String, Object>> jsonData, HttpServletRequest request) {
        BaseResult ret = null;
        try {
            ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
            ret = cooTaskUserTableService.saveFormData(oaUser, jsonData);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setStatus("0");
            ret.setMsg("系统异常");
        }
        return ret;
    }


    //-------------------------扩展字段的基本增删改查-----------------------

    /**
     * 首页
     *
     * @param model
     * @param request
     * @return
     */
    @OaUserPermission(value = "/cootasktable/index")
    @RequestMapping(value = "/index")
    public ModelAndView index(String fTaskHeadid, Model model, HttpServletRequest request) {
        model.addAttribute("fTaskHeadid", fTaskHeadid);
        return new ModelAndView("main/cootask/table/index");
    }

    /**
     * 列表数据
     *
     * @return
     */
    @RequestMapping(value = "/queryTable")
    @ResponseBody
    public Object queryTable(String page, String rows, CooTaskTable data) {
        Map<String, Object> parm = new HashMap<String, Object>();
        Map<String, Object> retD = new HashMap<String, Object>();
        // ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        parm.put("f_task_headID", data.getfTaskHeadid());
        try {
            PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
            List<CooTaskTable> list = cooTaskTableService.selectByParm(parm);
            PageInfo pageObj = new PageInfo(list);
            retD.put("total", pageObj.getTotal());
            retD.put("rows", list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retD;
    }

    /**
     * 修改或新增
     *
     * @return
     */
    @RequestMapping(value = "/saveTable")
    @ResponseBody
    public Object saveTable(@RequestBody CooTaskTable data, HttpServletRequest request) {
        BaseResult ret = null;
        try {
            ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
            ret = cooTaskTableService.saveTable(data, oaUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping(value = "/deleteTable")
    @ResponseBody
    public Object deleteTable(String id) {
        BaseResult ret = null;
        try {
            ret = cooTaskTableService.deleteTable(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
    //--------------- 扩展模板维护开始 ----------------

    //@OaUserPermission(value = "/cootasktable/tablebase")
    @RequestMapping(value = "/tablebaseindex")
    public ModelAndView tablebaseindex(HttpServletRequest request) {
        return new ModelAndView("main/cootask/table/tableBase");
    }

    @RequestMapping(value = "/tablebase", method = RequestMethod.GET)
    @ResponseBody
    public Object tablebase(String page, String rows, HttpServletRequest request) {
        Map<String, Object> retD = new HashMap<String, Object>();

        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));

        List<TaskTablebase> list = cooTaskTableService.tablebase();

        @SuppressWarnings({"rawtypes", "unchecked"})
        PageInfo pageObj = new PageInfo(list);
        retD.put("total", pageObj.getTotal());
        retD.put("rows", list);
        return retD;
    }


    @RequestMapping(value = "/tablebases", method = RequestMethod.GET)
    @ResponseBody
    public Object tablebases(String page, String rows, HttpServletRequest request) {
        List<TaskTablebase> list = cooTaskTableService.tablebase();
        return list;
    }


    @RequestMapping(value = "/tablebase", method = RequestMethod.POST)
    @ResponseBody
    public Object saveOrUpdateTablebase(TaskTablebase tb, HttpServletRequest request) {
        BaseResult br = null;
        try {
            br = cooTaskTableService.saveOrUpdateTablebase(tb);
        } catch (Exception e) {
            br = new BaseResult("0", "系统异常");
            e.printStackTrace();
        }
        return br;
    }

    @RequestMapping(value = "/deltablebase", method = RequestMethod.POST)
    @ResponseBody
    public Object deltablebase(String id, HttpServletRequest request) {
        BaseResult br = null;
        try {
            br = cooTaskTableService.deltablebase(id);
        } catch (Exception e) {
            br = new BaseResult("0", "系统异常");
            e.printStackTrace();
        }
        return br;
    }


    @RequestMapping(value = "/tablebasedetail", method = RequestMethod.GET)
    @ResponseBody
    public Object tablebasedetail(String page, String rows, String tablebaseID, HttpServletRequest request) throws Exception {
        Map<String, Object> retD = new HashMap<String, Object>();

        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));

        List<TaskTablebaseDetail> list = cooTaskTableService.tablebasedetail(tablebaseID);

        @SuppressWarnings({"rawtypes", "unchecked"})
        PageInfo pageObj = new PageInfo(list);
        retD.put("total", pageObj.getTotal());
        retD.put("rows", list);
        return retD;
    }

    @RequestMapping(value = "/tablebasedetail", method = RequestMethod.POST)
    @ResponseBody
    public Object tablebasedetail(TaskTablebaseDetail ttd, HttpServletRequest request) {
        BaseResult br = null;
        try {
            br = cooTaskTableService.tablebasedetail(ttd);
        } catch (Exception e) {
            br = new BaseResult("0", "系统异常");
            e.printStackTrace();
        }
        return br;
    }

    @RequestMapping(value = "/deltablebasedetail", method = RequestMethod.POST)
    @ResponseBody
    public Object deltablebasedetail(String id, HttpServletRequest request) {
        BaseResult br = null;
        try {
            br = cooTaskTableService.deltablebasedetail(id);
        } catch (Exception e) {
            br = new BaseResult("0", "系统异常");
            e.printStackTrace();
        }
        return br;
    }


    @RequestMapping(value = "/importExcel")
    @ResponseBody
    public Object importExcel(@RequestParam("id") String id,HttpServletRequest request) {
//        System.out.println("------->"+id);
        BaseResult br = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
//            System.out.println(mf.toString());
            String fileName = mf.getOriginalFilename();
//            System.out.println(fileName);
            try {
                br = cooTaskTableService.importExcel(id,mf);
            } catch (Exception e) {
                br = new BaseResult("0", "系统异常");
                e.printStackTrace();
            }
        }
        return br;
    }
}
